#!/usr/bin/env python
# coding=utf-8
from pyquery import PyQuery as pq
import requests

# 2.初始化
# --字符串初始化
html = '''
<div>
    <ul>
         <li class="item-0">first item</li>
         <li class="item-1"><a href="link2.html">second item</a></li>
         <li class="item-0 active"><a href="link3.html"><span class="bold">third item</span></a></li>
         <li class="item-1 active"><a href="link4.html">fourth item</a></li>
         <li class="item-0"><a href="link5.html">fifth item</a></li>
     </ul>
 </div>
'''
doc = pq(html)
print('字符串初始化')
print(doc('li'))

# --url初始化
doc = pq(url='https://cuiqingcai.com')
# doc=pq(requests.get('https://cuiqingcai.com').text) #等价效果
print('url初始化')
print(doc('title'))

# --文件初始化
doc = pq(filename='test.html')
print('文件初始化')
print(doc('li'))

# 3.基本css选择器
html = '''
<div id="container">
    <ul class="list">
         <li class="item-0">first item</li>
         <li class="item-1"><a href="link2.html">second item</a></li>
         <li class="item-0 active"><a href="link3.html"><span class="bold">third item</span></a></li>
         <li class="item-1 active"><a href="link4.html">fourth item</a></li>
         <li class="item-0"><a href="link5.html">fifth item</a></li>
     </ul>
 </div>
'''
doc = pq(html)
print('基本css选择器')
print(doc('#container .list li'))
print(type(doc('#container .list li')))

# 4. 查找节点
# --子节点
doc = pq(html)
items = doc('.list')  # 传入css选择器类参数
print('子节点')
print(type(items))
lis = items.find('li')  # 查找子节点需要用find()方法
print(type(lis))
print(lis)
lis = items.children('.active')
print(lis)

# --父节点
html = '''
<div class="wrap">
    <div id="container">
        <ul class="list">
             <li class="item-0">first item</li>
             <li class="item-1"><a href="link2.html">second item</a></li>
             <li class="item-0 active"><a href="link3.html"><span class="bold">third item</span></a></li>
             <li class="item-1 active"><a href="link4.html">fourth item</a></li>
             <li class="item-0"><a href="link5.html">fifth item</a></li>
         </ul>
     </div>
 </div>
'''
doc = pq(html)
items = doc('.list')
container = items.parent()
print('parent()方法获得直接父节点')
print(type(container))
print(container)
parents=items.parents() #获得祖先节点
print('获得祖先节点')
print(parents)
